//
//  MWShowroomController.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/10.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWShowroomController.h"
#import "MWShowroomGoodsController.h"
#import "MWHomeSearchController.h"

#import "MWShowroomInfoCell.h"
#import "MWShowroomCommonCell.h"
#import "MWDropMenuView.h"

#import <MapKit/MapKit.h>
@interface MWShowroomController () <UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong) UITableView *tableView;
@end

@implementation MWShowroomController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [[MWConfigManager manager] objectForKey:@"showroom" defaultValue:@"展厅"];
    [self setupPageSubviews];
    [self layoutPageSubviews];
}

-(void)searchAvtion:(UIButton *)sender {
    MWHomeSearchController *controller = [[MWHomeSearchController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - 请求展厅列表
- (void)loadShowroomList {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];
    
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];

    [[MWNetworkManager manager] POST:kShowroomListUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        if (code == 1) {
//            [self.showroomArray addObjectsFromArray:[MWShowroomModel mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]]];
        } else {
        
        }
        [self.tableView reloadData];
        [hud hideAnimated:YES];
    } failure:^(NSError *error) {
        [self.tableView reloadData];
        [hud hideAnimated:YES];
    }];
}

#pragma mark - UITableViewDataSource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([MWConfigManager manager].isNetError) {
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        tableView.hidden = YES;
    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        tableView.hidden = NO;
    }

    return 2;
}

- (void)refresh {
    [super refresh];
    [self loadShowroomList];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section % 2 == 0) {
        return 1;
    }
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
   return 0.1f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    if (section % 2 == 0) {
        headerView.backgroundColor = MWHexColor(@"#F6F7FB");
    } else {
        headerView.backgroundColor = MWHexColor(@"#FFFFFF");
    }
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section  % 2 == 0) {
        static NSString *identifier = @"MWShowroomInfoCell";
        MWShowroomInfoCell *infoCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!infoCell) {
            infoCell = [[MWShowroomInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            infoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [infoCell setupData:self.showroom];
        return infoCell;
        
    } else {
        static NSString *identifier = @"MWShowroomCommonCell";
        MWShowroomCommonCell *commonCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!commonCell) {
            commonCell = [[MWShowroomCommonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            commonCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.row % 2 == 0) {
            commonCell.iconIV.image = [UIImage imageNamed:@"ic_showroom_address"];
            commonCell.titleLB.text = self.showroom.location;
        } else {
            commonCell.iconIV.image = [UIImage imageNamed:@"ic_showroom_link"];
            commonCell.titleLB.text = [[MWConfigManager manager] objectForKey:@"recome_good_link" defaultValue:@"推荐商品链接"];
        }
        return commonCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section % 2 == 1) {
        if (indexPath.row == 0) {
            [self openMaps];
            
        } else if (indexPath.row == 1) {
            MWShowroomGoodsController *controller = [[MWShowroomGoodsController alloc] init];
            controller.showroom = self.showroom.name;
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

- (void)openMaps {
    NSString *hint = [[MWConfigManager manager] objectForKey:@"hint" defaultValue:@"提示"];
    NSString *hintMsg = [[MWConfigManager manager] objectForKey:@"hintMsg" defaultValue:@"导航将会跳转到第三方App"];
    NSString *hintCancel = [[MWConfigManager manager] objectForKey:@"cancel" defaultValue:@"取消"];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:hint message:hintMsg preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:hintCancel style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:cancel];
    
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        NSString *mapStr = [[MWConfigManager manager] objectForKey:@"amap" defaultValue:@"高德地图"];
        UIAlertAction *amap = [UIAlertAction actionWithTitle:mapStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self jumpToAmap];
        }];
        [alertVC addAction:amap];
    }
    
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        NSString *mapStr = [[MWConfigManager manager] objectForKey:@"baidumap" defaultValue:@"百度地图"];
        UIAlertAction *baidu = [UIAlertAction actionWithTitle:mapStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self jumpToBaiduMap];
        }];
        [alertVC addAction:baidu];

    }
    
    NSString *mapStr = [[MWConfigManager manager] objectForKey:@"maps" defaultValue:@"苹果地图"];
    UIAlertAction *appleMap = [UIAlertAction actionWithTitle:mapStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self jumpToAppleMap];
    }];
    [alertVC addAction:appleMap];
    [self presentViewController:alertVC animated:YES completion:nil];

}

#pragma mark - 跳转到高德地图
/*
 sourceApplication=%@&backScheme=%@
 sourceApplication代表你自己APP的名称，会在之后跳回的时候显示出来，所以必须填写。backScheme是你APP的URL Scheme，不填是跳不回来的
 dev=0
 这里填0就行了，跟百度地图的gcj02一个意思 ，1代表wgs84， 也用不上。
 */
- (void)jumpToAmap {
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]){
        //地理编码器
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        //我们假定一个终点坐标，上海嘉定伊宁路2000号报名大厅:121.229296,31.336956
        [geocoder geocodeAddressString:self.showroom.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            for (CLPlacemark *placemark in placemarks){
                //坐标（经纬度)
                CLLocationCoordinate2D coordinate = placemark.location.coordinate;
                NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",@"导航",@"AmapScheme",coordinate.latitude, coordinate.longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:nil];
                } else {
                    // Fallback on earlier versions
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
                }
            }
        }];
    }else{
        NSLog(@"您的iPhone未安装高德地图，请进行安装！");
    }
}
#pragma mark - 跳转到百度地图
/*
 1，origin={{我的位置}}, 这个是不能被修改的，不然无法把出发位置设置为当前位置
 2，destination = latlng:%f,%f|name = 目的地
 这里面的 name 的字段不能省略，否则导航会失败，而后面的文字则可以随意
 3，coord_type = gcj02
 coord_type 允许的值为 bd09ll、gcj02、wgs84，如果你 APP 的地图 SDK 用的是百度地图 SDK，请填 bd09ll，否则就填gcj02，wgs84的话基本是用不上了（需要涉及到地图加密）
 */
- (void)jumpToBaiduMap {
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]){
        //地理编码器
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        //我们假定一个终点坐标，上海嘉定伊宁路2000号报名大厅:121.229296,31.336956
        [geocoder geocodeAddressString:self.showroom.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            for (CLPlacemark *placemark in placemarks){
                //坐标（经纬度)
                CLLocationCoordinate2D coordinate = placemark.location.coordinate;
                NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",coordinate.latitude, coordinate.longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:nil];
                } else {
                    // Fallback on earlier versions
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
                }
            }
        }];
    }else{
        //添加提示
        NSLog(@"您的iPhone未安装百度地图，请进行安装！");
    }
}
#pragma mark - 跳转到苹果地图
- (void)jumpToAppleMap {
    
    //这个判断其实是不需要的
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]]){
        //MKMapItem 使用场景: 1. 跳转原生地图 2.计算线路
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];

        //地理编码器
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        //我们假定一个终点坐标，上海嘉定伊宁路2000号报名大厅:121.229296,31.336956
        [geocoder geocodeAddressString:self.showroom.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            CLPlacemark *endPlacemark  = placemarks.lastObject;

            //创建一个地图的地标对象
            MKPlacemark *endMKPlacemark = [[MKPlacemark alloc] initWithPlacemark:endPlacemark];
            //在地图上标注一个点(终点)
            MKMapItem *endMapItem = [[MKMapItem alloc] initWithPlacemark:endMKPlacemark];

            //MKLaunchOptionsDirectionsModeKey 指定导航模式
            //NSString * const MKLaunchOptionsDirectionsModeDriving; 驾车
            //NSString * const MKLaunchOptionsDirectionsModeWalking; 步行
            //NSString * const MKLaunchOptionsDirectionsModeTransit; 公交
            [MKMapItem openMapsWithItems:@[currentLocation, endMapItem]
                           launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];

        }];
    }
    
}

#pragma mark - UI
- (void)setupPageSubviews {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 300;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    
}



- (void)layoutPageSubviews {
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.bottom.equalTo(self.view);
    }];
}

@end
